import { Scene, WebGLRenderer, PerspectiveCamera, Mesh, PlaneBufferGeometry, MeshPhongMaterial } from "three";
// import * as THREE from 'three'
let THREE=require('three');
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls"
import { FBXLoader } from "three/examples/jsm/loaders/FBXLoader.js"
import  LightMgr  from "./LightMgr";
import  SkyBoxMgr from "./SkyBoxMgr"
import { MD2CharacterComplex } from 'three/examples/jsm/misc/MD2CharacterComplex.js';
import { Gyroscope } from 'three/examples/jsm/misc/Gyroscope.js';
// import { SupLoader } from "./SupMgr";
// import { Object3D } from "three/build/three.module";
// import { LoaderUtils } from "three/build/three.module";
// import { TGALoader } from "three/examples/jsm/loaders/TGALoader";


// const skyBoxbaseUrl="http://iddd.oss-cn-shanghai.aliyuncs.com/sheji/public/model/iddd/skyboxs/sky5/";
// const fbxbaseUrl="http://iddd.oss-cn-shanghai.aliyuncs.com/sheji/public/model/";
// const baseUrl = "http://iddd.oss-cn-shanghai.aliyuncs.com/LocalDB/ShareModel/";
// let url = window.location.href;
// let par = url.split('?')[1];
// let id = par.split('=')[1];
// let supUrl = baseUrl + id + ".sup";
// let buildingUlr = baseUrl + id + ".fbx";
// let supLoader = new SupLoader(supUrl);
// let materialMgr = supLoader.materialMgr;

class MainScene extends Scene {

  static  _that;

    constructor() {

        super();

        MainScene._that=this;
        this.MoveControls = {
          moveForward: false,
          moveBackward: false,
          moveLeft: false,
          moveRight: false
        };

        this.renderer = this.createWebGLRenderer();

        this.camera = this.createPerspectiveCamera();

        this.orbitControls=this.createOrbitControls();


        //创建太阳光
        this.sunlight=LightMgr.getInstance().createLight('DirectionalLight');
        // this.sunLightHelper = new THREE.DirectionalLightHelper(this.sunlight, 5 );
        this.add(this.sunlight);
        // this.add(this.sunLightHelper );




        //创建HemisphereLight
        this.hemisphereLight=LightMgr.getInstance().createLight('HemisphereLight');
        this.add(this.hemisphereLight);

        //创建AmbientLight
      // this.ambientLight=LightMgr.getInstance().createLight('AmbientLight');
      // this.add(this.ambientLight);

        let view = this;
        let onWindowResize = function () {
            let { camera, renderer } = view;
            camera.aspect = window.innerWidth / window.innerHeight;
            camera.updateProjectionMatrix();
            renderer.setSize(window.innerWidth, window.innerHeight);
        }
        window.addEventListener('resize', onWindowResize, false);
    }


  createCharacter(baseUrl="ogro/") {
    // CHARACTER
    let configOgro = {
      baseUrl: baseUrl,
      body: "ogro.md2",
      skins: ["grok.jpg", "ogrobase.png", "arboshak.png", "ctf_r.png", "ctf_b.png", "darkam.png", "freedom.png",
        "gib.png", "gordogh.png", "igdosh.png", "khorne.png", "nabogro.png",
        "sharokh.png"],
      weapons: [["weapon.md2", "weapon.jpg"]],
      animations: {
        move: "run",
        idle: "stand",
        jump: "jump",
        attack: "attack",
        crouchMove: "cwalk",
        crouchIdle: "cstand",
        crouchAttach: "crattack"
      },
      walkSpeed: 10,
      crouchSpeed: 20
    };
    this.character = new MD2CharacterComplex();
    this.character.scale = 0.1;
    this.character.posiiton = new THREE.Vector3(0, 0, 0);
    this.character.controls = this.MoveControls;
    this.character.onLoadComplete = () => {
      // cast and receive shadows
      // this.character.enableShadows(true);
      this.character.setWeapon(0);
      this.character.setSkin(0);
      this.character.root.position.y = 2.2;
      this.character.root.position.x = 0;
      this.character.root.position.z = 0;
      this.add(this.character.root);
      let gyro = new Gyroscope();
      gyro.add(this.camera);
      this.character.root.add(gyro);
      this.character.root.name="Character";
    };
    this.character.loadParts(configOgro);
  }

//创建渲染器
    createWebGLRenderer(){
      let renderer = new WebGLRenderer({
        antialias: true
      });
      renderer.setPixelRatio(window.devicePixelRatio);
      renderer.setSize(window.innerWidth, window.innerHeight);
      renderer.shadowMap.enabled = true;
      renderer.domElement.lineWidth = 0;
      return renderer;
    }



    //创建透视相机
    createPerspectiveCamera()
    {
      let camera = new PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
      camera.position.set(-10, 10, 30);
      return camera;
    }

    //创建orbitControls 可以对三维场景进行缩放、平移、旋转操作
    createOrbitControls(){
      let controls = new OrbitControls(this.camera,  this.renderer.domElement);
      controls.target.set(0, 0, 0);
      controls.update();
      return controls;
    }



    createSkyBox(skyBoxurl)
    {
      //创建天空盒
      this.background=SkyBoxMgr.getInstance().createSkyBox(skyBoxurl)
      // this.background = new Color(0xa0a0a0);

    }



    createPlane() {
        var mesh = new Mesh(new PlaneBufferGeometry(200, 200), new MeshPhongMaterial({
            color: 0x808080,
            depthWrite: false
        }));
        mesh.rotation.x = -Math.PI / 2;
        mesh.receiveShadow = true;
        this.add(mesh);
    }


    test() {
        // console.log(Object3D);
        // console.log(buildingUlr);
        // let loader = new FBXLoader();
        // let url = "http://192.168.1.188:10077/d__191207_3314/d__191207_3314.fbx"
        // loader.resourcePath = LoaderUtils.extractUrlBase(url) + "Texture2D/";
        // // let tgaLoader = new TGALoader();
        // let tgaLoader = new TGALoader();
        // tgaLoader.setPath(loader.resourcePath);
        // // THREE.Loader.Handlers.add(/\.tga$/i, tgaLoader);
        // loader.manager.addHandler(/\.tga$/i, tgaLoader)
        // let scene = this;
        // loader.load(url, function (obj) { scene.add(obj) });

    }



    init() {
        // this.add(supLoader.productMgr.root);
        // supLoader.init(() => this.loadBuilding(buildingUlr));
        // // supLoader.init(() => this.test());
    }


    /**
     * 加载建筑
     * @param {string} url
     */

    loadBuilding(url,supLoader) {
        let view = this;
        let loader = new FBXLoader();
        console.log('loadBuilding:'+url)
        loader.load(url, function (object) {
            object.traverse(function (child) {
                // console.log(child);
                if (child.isMesh) {
                    child.castShadow = true;
                    // child.receiveShadow = true;
                    // console.log("child.name")
                    // console.log(child.name)
                    let material = supLoader.materialMgr.getMaterial(child.name);
                    if (material != null)
                        child.material = material;
                }
            });
            view.add(object);
            object.rotateY(THREE.MathUtils.degToRad(180));
            console.log(object.rotation.toVector3());
            // view.add(object.children[0])
        })
    }

    update() {
      this.renderer.render(this, this.camera);
    }




    onKeyDown( event ) {

      switch ( event.keyCode ) {

        case 38: /*up*/
        case 87: /*W*/ 	 MainScene._that.MoveControls.moveForward = true; break;

        case 40: /*down*/
        case 83: /*S*/ 	  MainScene._that.MoveControls.moveBackward = true; break;

        case 37: /*left*/
        case 65: /*A*/  MainScene._that.MoveControls.moveLeft = true; break;

        case 39: /*right*/
        case 68: /*D*/  MainScene._that.MoveControls.moveRight = true; break;

        //case 67: /*C*/     MainScene._that.MoveControls.crouch = true; break;
        //case 32: /*space*/ MainScene._that.MoveControls.jump = true; break;
        //case 17: /*ctrl*/  MainScene._that.MoveControls.attack = true; break;

      }

  }

    onKeyUp( event ) {

    switch ( event.keyCode ) {

      case 38: /*up*/
      case 87: /*W*/  MainScene._that.MoveControls.moveForward = false; break;

      case 40: /*down*/
      case 83: /*S*/ 	  MainScene._that.MoveControls.moveBackward = false; break;

      case 37: /*left*/
      case 65: /*A*/ 	  MainScene._that.MoveControls.moveLeft = false; break;

      case 39: /*right*/
      case 68: /*D*/  MainScene._that.MoveControls.moveRight = false; break;

      //case 67: /*C*/     MainScene._that.MoveControls.crouch = false; break;
      //case 32: /*space*/ MainScene._that.MoveControls.jump = false; break;
      //case 17: /*ctrl*/  MainScene._that.MoveControls.attack = false; break;

    }

  }

}

export default MainScene
